package cn.nfwx.tv.db;

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;

import cn.nfwx.tv.util.LogUtil;

@Database(entities = {DownProgramModel.class, TsProgramModel.class, TvAppointment.class},
        version = AppDatabase.DB_VERSION)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;
    private static final String DB_NAME = "nfwx_new.db";
    public static final int DB_VERSION = 2;
    private static final Object sLock = new Object();

    public static AppDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (sLock) {
                if (INSTANCE == null) {
                    INSTANCE =
                            Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME)
                                    .allowMainThreadQueries()
                                    .fallbackToDestructiveMigration()//迁移数据库如果发生错误，将会重新创建数据库，而不是发生崩溃
                                    .build();

                }
            }
        }
        return INSTANCE;
    }

    public abstract DownProgramDao programDao();

    public abstract TsDao tsDao();

    public abstract AppointDao appointDao();

    public void closeDb() {
        INSTANCE = null;
    }
}
